package co.chuangdian.oflauncher.widgets.system;

import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import co.chuangdian.oflauncher.R;

public class MusicAdapter extends BaseAdapter {

	private Context mContext;
	private List<Music> data_list;

	public MusicAdapter(Context context) {
		init(context);
	}

	public MusicAdapter(Context context, List<Music> list) {
		data_list = list;
		init(context);
	}

	private void init(Context context) {
		mContext = context;
		if (data_list == null) {
			data_list = MusicList.getInstance(mContext).getMusicList();
		}
	}

	@Override
	public int getCount() {
		if (data_list == null) {
			return 0;
		}
		return data_list.size();
	}

	@Override
	public Music getItem(int position) {
		if (data_list == null) {
			return null;
		}
		return data_list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
		if (convertView == null) {
			holder = new ViewHolder();
			LayoutInflater inflater = LayoutInflater.from(mContext);
			convertView = inflater.inflate(R.layout.music_list_item, parent, false);
			// convertView = inflater.inflate(R.layout.music_list_item, null);
			holder.title = (TextView) convertView.findViewById(R.id.music_title);
			holder.icon = (ImageView) convertView.findViewById(R.id.music_icon);
			holder.name = (TextView) convertView.findViewById(R.id.music_name);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		Music music = data_list.get(position);
		holder.title.setText(music.getTitle());

		String albumArt = getAlbumArt(music.getAlbumId());
		if (albumArt == null) {
			holder.icon.setImageResource(R.drawable.music_default_icon);
		} else {
			Bitmap bm = BitmapFactory.decodeFile(albumArt);
			holder.icon.setImageBitmap(bm);
		}

		holder.name.setText(music.getSinger());
		return convertView;
	}

	class ViewHolder {
		private TextView title;
		private TextView name;
		private ImageView icon;

	}

	private String getAlbumArt(int album_id) {
		String mUriAlbums = "content://media/external/audio/albums";
		String[] projection = new String[] { "album_art" };
		Cursor cur = mContext.getContentResolver().query(Uri.parse(mUriAlbums + "/" + Integer.toString(album_id)),
				projection, null, null, null);
		String album_art = null;
		if (cur.getCount() > 0 && cur.getColumnCount() > 0) {
			cur.moveToNext();
			album_art = cur.getString(0);
		}
		cur.close();
		cur = null;
		return album_art;
	}
}
